import React, { useState } from 'react';
import { Upload, Button, message, Avatar, Row, Col } from 'antd';
import { UserOutlined, UploadOutlined } from '@ant-design/icons';
import type { UploadFile } from 'antd/es/upload/interface';
import Cropper from 'react-cropper';
import 'cropperjs/dist/cropper.css';
import { accountService } from '@/services/accountService';
import http from '@/http';
import styles from './AvatarUpload.module.css';

interface AvatarUploadProps {
  onUpdate: (avatarUrl: string) => void;
  currentAvatar?: string;
}

const AvatarUpload: React.FC<AvatarUploadProps> = ({ onUpdate, currentAvatar }) => {
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [cropper, setCropper] = useState<any>(null);
  const [croppedImage, setCroppedImage] = useState<string>('');
  const [loading, setLoading] = useState(false);

  const handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj!);
    }
    setPreviewImage(file.url || (file.preview as string));
    setPreviewVisible(true);
  };

  const handleChange = ({ fileList }: { fileList: UploadFile[] }) => {
    // 只保留最新上传的文件
    setFileList(fileList.slice(-1));
    
    // 如果有文件，自动打开裁剪窗口
    if (fileList.length > 0 && fileList[0].originFileObj) {
      handlePreview(fileList[0]);
    }
  };

  const getBase64 = (file: File): Promise<string> => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result as string);
      reader.onerror = error => reject(error);
    });
  };

  const handleCrop = () => {
    if (cropper) {
      const canvas = cropper.getCroppedCanvas();
      const croppedImageUrl = canvas.toDataURL('image/jpeg');
      setCroppedImage(croppedImageUrl);
      setPreviewVisible(false);
    }
  };

  const handleUpload = async () => {
    if (!croppedImage) {
      message.error('请先裁剪图片');
      return;
    }

    try {
      setLoading(true);
      // 将base64转换为Blob
      const base64Data = croppedImage.split(',')[1];
      const blob = await fetch(`data:image/jpeg;base64,${base64Data}`).then(res => res.blob());
      
      // 创建FormData
      const formData = new FormData();
      formData.append('avatar', blob, 'avatar.jpg');

      // 上传头像
      const response = await accountService.uploadAvatar(formData);
      onUpdate(response.data.avatar_url);
      setCroppedImage('');
      setFileList([]);
      message.success('头像上传成功');
    } catch (error) {
      message.error('头像上传失败');
    } finally {
      setLoading(false);
    }
  };

  const handleReset = () => {
    setCroppedImage('');
    setFileList([]);
    setPreviewVisible(false);
    setPreviewImage('');
  };

  const uploadButton = (
    <div>
      <UploadOutlined />
      <div style={{ marginTop: 8 }}>上传图片</div>
    </div>
  );

  return (
    <div className={styles.container}>
      <Row gutter={24} className={styles.avatarRow}>
        <Col xs={24} md={12} className={styles.leftCol}>
          <div className={styles.uploadSection}>
            <h3>上传新头像</h3>
            <p className={styles.tips}>
              支持JPG、PNG、GIF、WEBP格式，大小不超过8MB
            </p>
            
            {previewVisible ? (
              <div className={styles.cropperWrapper}>
                <Cropper
                  src={previewImage}
                  style={{ height: 300, width: '100%' }}
                  aspectRatio={1}
                  guides={true}
                  onInitialized={(instance) => setCropper(instance)}
                />
                <div className={styles.cropperActions}>
                  <Button 
                    onClick={() => setPreviewVisible(false)} 
                    style={{ marginRight: 8 }}
                  >
                    取消
                  </Button>
                  <Button type="primary" onClick={handleCrop}>
                    确认裁剪
                  </Button>
                </div>
              </div>
            ) : (
              <>
                <Upload
                  listType="picture-card"
                  fileList={fileList}
                  onPreview={handlePreview}
                  onChange={handleChange}
                  beforeUpload={(file) => {
                    const isValidType = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'].includes(file.type);
                    const isLt8M = file.size / 1024 / 1024 < 8;
                    
                    if (!isValidType) {
                      message.error('只支持JPG、PNG、GIF、WEBP格式的图片');
                    }
                    
                    if (!isLt8M) {
                      message.error('图片大小不能超过8MB');
                    }
                    
                    if (isValidType && isLt8M) {
                      return false; // 手动处理上传
                    }
                    
                    return Upload.LIST_IGNORE;
                  }}
                  maxCount={1}
                  className={styles.uploadBox}
                >
                  {fileList.length >= 1 ? null : uploadButton}
                </Upload>
                
                {croppedImage && (
                  <div className={styles.previewSection}>
                    <h3>裁剪预览</h3>
                    <div className={styles.previewImage}>
                      <img src={croppedImage} alt="预览" className={styles.cropPreview} />
                    </div>
                    <div className={styles.buttonContainer}>
                      <Button
                        onClick={handleReset}
                        style={{ marginRight: 16 }}
                        disabled={loading}
                      >
                        重置
                      </Button>
                      <Button
                        type="primary"
                        onClick={handleUpload}
                        loading={loading}
                        className={styles.uploadButton}
                      >
                        上传头像
                      </Button>
                    </div>
                  </div>
                )}
              </>
            )}
          </div>
        </Col>
        
        <Col xs={24} md={12} className={styles.rightCol}>
          <div className={styles.sizePreviewSection}>
            <h3>头像预览</h3>
            <p className={styles.previewDesc}>头像将按照以下尺寸展示在平台的不同位置</p>
            
            <div className={styles.sizeList}>
              <div className={styles.sizeItem}>
                <span className={styles.sizeLabel}>大尺寸</span>
                <Avatar 
                  size={110} 
                  src={croppedImage || (currentAvatar ? http.getBaseURL() + currentAvatar : undefined)} 
                  icon={<UserOutlined />}
                  className={styles.largeAvatar}
                />
              </div>
              
              <div className={styles.sizeItem}>
                <span className={styles.sizeLabel}>中尺寸</span>
                <Avatar 
                  size={64} 
                  src={croppedImage || (currentAvatar ? http.getBaseURL() + currentAvatar : undefined)} 
                  icon={<UserOutlined />}
                  className={styles.mediumAvatar}
                />
              </div>
              
              <div className={styles.sizeItem}>
                <span className={styles.sizeLabel}>小尺寸</span>
                <Avatar 
                  size={40} 
                  src={croppedImage || (currentAvatar ? http.getBaseURL() + currentAvatar : undefined)} 
                  icon={<UserOutlined />}
                  className={styles.smallAvatar}
                />
              </div>
            </div>
          </div>
        </Col>
      </Row>
    </div>
  );
};

export default AvatarUpload; 